#/bin/bash

VERSION_STR="1.0.0"
RELATIVE_DIR=""
function now_dir() {
    DIRS=("" "../")
    for D in ${DIRS[*]}; do
        if [ -f "${D}version" ]; then
            RELATIVE_DIR=${D}
            break
        fi
    done
}

## load version
function read_version() {
    VERSION_STR=$(cat ${RELATIVE_DIR}version)
    echo "release version: ${VERSION_STR}"
}

## npm build
function npm_build() {
    export VERSION=${VERSION_STR}
    npm run build
}

## replace version
function replace_version_before_sign() {
    sed -i "" "s/\"version\": \"1.0.0\"/\"version\": \"${VERSION_STR}\"/g" ${RELATIVE_DIR}dist/plugin.json
}

## sign
function sign() {
    source ${RELATIVE_DIR}.env
    npm run sign
}

## update version
function update_version() {
    version_str=${VERSION_STR#*v}
    MAJOR=$(echo $version_str | cut -d '.' -f 1)
    MINOR=$(echo $version_str | cut -d '.' -f 2)
    PATCH=$(echo $version_str | cut -d '.' -f 3)
    PATCH=$(expr ${PATCH} + 1)
    VERSION_NEW="${MAJOR}.${MINOR}.${PATCH}"

    cat /dev/null >${RELATIVE_DIR}version && echo ${VERSION_NEW} >${RELATIVE_DIR}version
    git commit -m 'bump version'
}

now_dir
read_version
npm_build
replace_version_before_sign
# sign
# update_version
